﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApi02.Domain;
using WebApi02.Interface;

namespace WebApi02.Implementation
{
    //必须是泛型
    
    public class EfRespository<T> : IRespository<T> where T : BaseEntity
    {
        private readonly Admin02Dbcontent db;
        
        private DbSet<T> _entity;
        private DbSet<T> Entity 
        {
            get
            {
                if(_entity == null)
                {
                    _entity = db.Set<T>();
                }
                return Entity;
            }
        }  

        public IQueryable<T> Table
        {
            get
            {
                
                return Entity;
            }
        }
        public EfRespository(Admin02Dbcontent dbContext)
        {
            db = dbContext;
        }
        public void Delete(T entity)
        {
            //throw new NotImplementedException();
            this._entity.Remove(entity);

            db.SaveChanges();
        }

        public void Delete(int id)
        {
            //throw new NotImplementedException();
            var row = Table.Where(x => x.Id == id).FirstOrDefault();
            Delete(row);
        }

        public T GetById(int id)
        {
            return _entity.Where(x => x.Id == id).FirstOrDefault();
           
        }

        public void Insert(T entity)
        {
            _entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBulk(IEnumerable<T> list)
        {
            //throw new NotImplementedException();
            _entity.AddRange(list);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            _entity.Update(entity);
            db.SaveChanges();
        }
    }
}
